<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-12-19 20:35:43
 * @LastEditors: Andy
 * @LastEditTime: 2023-04-06 11:06:11
-->
<template>
  <div class="role-info-container">
    <div class="info-hearder flex-row">
      <img src="../../../common/assets/images/role-default.png" alt="" />
      <div class="base-info flex-column">
        <span class="title"
          >{{ roleInfo?.roleName ?? '' }}
          <el-tag v-if="roleInfo?.orgName || deptName" size="mini">{{
            deptName ? deptName : roleInfo?.orgName
          }}</el-tag>
        </span>
        <span>{{ roleInfo?.remark ?? '' }}</span>
      </div>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick" class="role-auth-tab">
      <el-tab-pane label="功能权限" name="first"></el-tab-pane>
      <el-tab-pane label="数据权限" name="second"></el-tab-pane>
    </el-tabs>
    <div class="role-perm-content flex-column" v-show="activeName === 'first'">
      <div class="flex-row">
        <label class="form-label">所属端:</label>
        <x-radio-group :list-data="clientOptions" :prop-object="clientProps" v-model="checkVal" />
      </div>
      <el-scrollbar
        class="x-tree-container"
        v-loading="scopeLoading"
        :element-loading-text="$t('common.loading')"
        element-loading-spinner="el-icon-loading"
      >
        <el-tree
          v-if="functionTreeOptions.length"
          class="menuTree"
          :data="functionTreeOptions"
          show-checkbox
          ref="functionScopeTree"
          node-key="value"
          :height="300"
          :highlight-current="true"
          :expand-on-click-node="false"
          :props="defaultProps"
          @check="handleCheckChange"
          @node-expand="handleNodeExpand"
          :render-content="renderContent"
        >
        </el-tree>
        <x-empty-text v-else></x-empty-text>
      </el-scrollbar>
    </div>
    <div class="role-data-content flex-column" v-if="activeName === 'second'">
      <div class="form-item flex-column">
        <div class="flex-row">
          <label class="form-label">数据范围:</label>
          <x-radio-group :list-data="dataOptions" v-model="selectVal" />
        </div>
      </div>
      <!---仅限自定义时展示 --->
      <el-scrollbar
        class="x-tree-container"
        v-show="selectVal === '5' && activeName === 'second'"
        v-loading="deptLoading"
        :element-loading-text="$t('common.loading')"
        element-loading-spinner="el-icon-loading"
      >
        <el-tree
          v-if="deptData.length"
          show-checkbox
          :props="defaultProps"
          ref="dataScopeTree"
          node-key="value"
          :data="deptData"
          :expand-on-click-node="false"
          default-expand-all
          :highlight-current="true"
          @check="handleCheckDataChange"
        ></el-tree>
        <x-empty-text v-else></x-empty-text>
      </el-scrollbar>
    </div>
  </div>
</template>
<script lang="jsx">
  import { cloneDeep } from '@package/utils'
  import { apiGetMenuTree, apiPostApplication } from '@/modules/auth/api'
  import { apiPostDeptTree } from '@/modules/organization/api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  export default {
    name: 'RoleAuthInfo',
    props: {
      mode: {
        // 当前是否可选择权限
        type: String,
        default: 'edit'
      },
      roleInfo: {
        type: Object,
        default: () => ({})
      },
      deptName: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        activeName: 'first',
        selectVal: '',
        dataOptions: [
          {
            label: '本人',
            value: '1'
          },
          {
            label: '本部门',
            value: '2'
          },
          {
            label: '本部门及下属子部门',
            value: '3'
          },
          {
            label: '全部',
            value: '4'
          },
          {
            label: '自定义',
            value: '5'
          }
        ],
        functionTreeOptions: [],
        functionKeys: [],
        defaultProps: {
          label: 'label',
          children: 'children'
        },
        scopeLoading: false,
        deptLoading: false,
        dataTreeOptions: [],
        dataKeys: [],
        expandKeys: [],
        deptData: [],
        renderContent(h, { node, data, store }) {
          // 树节点的内容区的渲染 Function
          let classname = ''
          let iconClass = ''
          // 由于项目中有三级菜单也有四级级菜单，就要在此做出判断
          if (`${data.menuType}` === '3') {
            classname = 'flex-node'
          } else {
            classname = 'menu-node'
            iconClass = 'iconfont icon-erjicaidan'
          }

          return (
            <div class={classname}>
              <i class={iconClass} />
              {node.label}
            </div>
          )
        },
        clientOptions: [],
        checkVal: '',
        checkName: '',
        clientProps: {
          label: 'clientName',
          value: 'clientId'
        },
        isDestory: true
      }
    },
    watch: {
      roleInfo: {
        handler(val) {
          if (val) {
            this.loadDeptTreeData(val.orgId)
            this.selectVal = `${val?.dsType}` ?? ''
            this.$nextTick(() => {
              this.functionKeys = cloneDeep(val.menus)
              this.dataKeys = cloneDeep(val.scopes)
              this.handleSetCheck()
            })
          }
        },
        immediate: true,
        deep: true
      },
      mode: {
        handler(val) {
          if (val === 'view') {
            this.setDisabled(this.functionTreeOptions)
            this.setDisabled(this.deptData)
          }
        }
      },
      checkVal: {
        handler(val) {
          if (this.checkVal) {
            this.loadFuncitonTree()
            this.checkName = this.clientOptions.filter((v) => v.clientId === this.checkVal)[0]?.clientName
          }
        },
        immediate: true,
        deep: true
      }
    },
    created() {
      this.isDestory = true
    },
    mounted() {
      // this.loadFuncitonTree()
      this.initClientOptions()
    },
    beforeDestroy() {
      this.isDestory = false
      console.log('this.isDestory: ', this.isDestory)
    },
    destroyed() {
      console.log('ddddd')
    },
    methods: {
      initClientOptions() {
        apiPostApplication({ data: {}, pageNum: 1, pageSize: 10 }).then(({ code, data }) => {
          if (code === EnumApiCode.Success) {
            this.clientOptions = data.list
            if (!this.checkVal) {
              this.checkVal = 'srm-manage'
            }
          }
        })
      },
      async loadFuncitonTree() {
        this.scopeLoading = true
        try {
          const { data } = await apiGetMenuTree({ clientId: this.checkVal })
          this.scopeLoading = false
          this.functionTreeOptions = data?.length
            ? JSON.parse(
                JSON.stringify(data)
                  .replace(/menuName/g, 'label')
                  .replace(/id/g, 'value')
              )
            : []
          this.$nextTick(() => {
            this.handleSetClass()
            this.handleSetCheck()
            if (this.mode === 'view') {
              this.setDisabled(this.functionTreeOptions)
            }
          })
        } finally {
          this.scopeLoading = false
        }
      },
      async loadDeptTreeData(orgId) {
        this.deptLoading = true
        apiPostDeptTree({ orgId })
          .then(({ code, data }) => {
            this.deptLoading = false
            if (code === EnumApiCode.Success) {
              this.deptData = JSON.parse(
                JSON.stringify(data)
                  .replace(/deptName/g, 'label')
                  .replace(/id/g, 'value')
              )
              if (this.mode === 'view') {
                this.setDisabled(this.deptData)
              }
            }
          })
          .catch(() => {
            this.deptLoading = false
          })
      },
      handleClick(tab) {
        this.activeName = tab.name
        if (this.activeName === 'second') {
          this.$nextTick(() => {
            this.$refs.dataScopeTree.setCheckedKeys(this.dataKeys)
          })
        }
      },
      handleSetCheck() {
        if (this.$refs?.functionScopeTree) {
          const checkKeys = cloneDeep(this.functionKeys)
          const result = checkKeys && checkKeys.length ? this.filterTreeData(checkKeys, this.functionTreeOptions) : []
          this.$refs.functionScopeTree.setCheckedKeys(result)
        }
        if (this.activeName === 'second' && this.$refs?.dataScopeTree) {
          this.$refs.dataScopeTree.setCheckedKeys(this.dataKeys || [])
        }
      },
      handleNodeCilck() {},
      handleCheckChange() {
        const result = this.$refs.functionScopeTree.getCheckedNodes(false, true)
        this.functionKeys = result.map((v) => v.value)
        // this.handleSetClass()
      },
      handleCheckDataChange() {
        const result = this.$refs.dataScopeTree.getCheckedNodes(false, true)
        this.dataKeys = result.map((v) => v.value)
        this.handleSetClass()
      },
      clearRoleAuth() {
        this.activeName = 'first'
        this.dataKeys = []
        this.functionKeys = []
        this.selectVal = '1'
      },
      handleSetClass() {
        this.$nextTick(() => {
          const btnNodes = document.getElementsByClassName('flex-node')
          for (let i = 0; i < btnNodes.length; i++) {
            btnNodes[i].parentNode.parentNode.parentNode.style.display = 'flex'
            btnNodes[i].parentNode.parentNode.parentNode.style.flexFlow = 'wrap'

            if (btnNodes[i].parentNode.parentNode.classList) {
              btnNodes[i].parentNode.parentNode.classList.add('btn-node')
            }
            // btnNodes[i].parentNode.onmouseover = function () {
            //   this.style.backgroundColor = '#fff'
            // }
            // const childrenNodes = btnNodes[i].parentNode.parentNode.parentNode.children
            // let isNum = 0
            // for (let j = 0; j < childrenNodes.length; j++) {
            //   if (childrenNodes[j].classList.value.indexOf('btn-node') !== -1) {
            //     childrenNodes[j].classList.remove('block-node')
            //     isNum++
            //   } else {
            //     childrenNodes[j].classList.add('block-node')
            //   }
            //   if (isNum > 1) {
            //     // console.log(childrenNodes[j], 'ppppppp')
            //     childrenNodes[j].classList.add('no-line')
            //   }
            // }
          }
          const menuNodes = document.getElementsByClassName('menu-node')
          for (let j = 0; j < menuNodes.length; j++) {
            menuNodes[j].parentNode.parentNode.style.flexBasis = '100%'
          }
        })

        // console.log(btnNodes)
      },
      handleNodeExpand(obj, node, event) {
        console.log('obj: ', obj)
        if (`${obj.menuType}` === '2') {
          const times = setTimeout(() => {
            event.$el.lastElementChild.style.display = 'flex'
            event.$el.lastElementChild.style.flexFlow = 'wrap'
            const menuNodes = document.getElementsByClassName('menu-node')
            for (let j = 0; j < menuNodes.length; j++) {
              menuNodes[j].parentNode.parentNode.style.flexBasis = '100%'
            }
            clearTimeout(times)
          })
        }
      },
      setDisabled(treeData) {
        treeData.forEach((item) => {
          this.$set(item, 'disabled', true)
          if (item.children) {
            this.setDisabled(item.children)
          }
        })
        return treeData
      },
      filterTreeData(checkedKeys, menus) {
        menus.forEach((item) => {
          if (checkedKeys.includes(item.value) && item.children.length) {
            checkedKeys.splice(checkedKeys.indexOf(item.value), 1)
          }
          if (item.children.length) {
            checkedKeys = this.filterTreeData(checkedKeys, item.children)
          }
        })
        return checkedKeys
      }
    }
  }
</script>
<style lang="scss" scoped>
  .role-info-container {
    display: flex;
    flex-direction: column;
    height: 100%;

    .info-hearder.flex-row {
      padding: 15px 15px 10px 15px;

      img {
        // width: 35px;
        height: 50px;
        border-radius: 50%;
      }

      .base-info {
        justify-content: center;
        padding-left: 20px;

        span {
          color: #333;

          &.title {
            font-size: 20px;
            font-weight: bold;
            line-height: 43px;
          }

          .el-tag--mini {
            line-height: 19px;
            height: 20px;
            margin-left: 8px;
            padding: 0 5px;
            color: #409eff;
          }
        }
      }
    }

    .role-data-content {
      color: #333;
      padding-top: 10px;
      flex: 1;
      overflow: hidden;
    }

    .role-perm-content {
      height: 100%;
      padding-top: 10px;
      overflow: hidden;

      .el-tree {
        // overflow-y: auto;
        // height: calc(100% - 200px);
        height: 100%;
      }
    }
    .form-label {
      line-height: 30px;
      margin-right: 16px;
      white-space: nowrap;
      color: #424242;
      padding-left: 23px;
    }
  }
  .x-tree-container.el-scrollbar {
    flex: 1;
  }
</style>
<style lang="scss">
  @import '../../../common/assets/style/tree';

  .role-auth-tab.el-tabs.el-tabs--top {
    display: flex;
    // flex: 1;
    flex-direction: column;
    // height: calc(100% - 145px);
    padding: 0 20px;
  }

  // .role-auth-tab.el-tabs.el-tabs--top .el-tabs__content {
  //   flex: 1;
  // }
  .role-auth-tab.el-tabs.el-tabs--top .el-tabs__header {
    margin-bottom: 0;
  }
  .roles-tab.el-tabs--card > .el-tabs__header {
    margin-bottom: 0;
  }

  .role-auth-tab .el-tabs__nav-wrap {
    padding-left: 15px;
  }

  .role-perm-content .el-tree-node.is-expanded > .el-tree-node__children {
    /* display: flex; */
  }
  .role-perm-content .el-tree-node.is-expanded.is-focusable > .el-tree-node__content {
    // padding: 5px 0;
  }
  .flex-node {
    // pointer-events: none;
    cursor: not-allowed;
  }

  .role-data-content .el-scrollbar {
    flex: 1;
  }
  /* element滚动条组件 隐藏水平滚动条 */
  .x-tree-container .el-scrollbar__view {
    height: 100%;
  }
  .role-data-content .el-scrollbar__view {
    padding: 0 15px;
  }

  .x-tree-container .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .role-data-content .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .is-horizontal {
    display: none;
  }

  .menuTree ::v-deep .el-tree-node__children .el-tree-node__children .el-tree-node {
    float: left;
  }
  .x-tree-container .el-scrollbar .collapse-transition {
    transition: none; //权重稍微高一点覆盖掉组件本身的动画效果
  }
</style>
